﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Runtime.Remoting.Messaging;
using System.Threading;
using System.Net;

namespace PADIbook
{
    delegate bool ConnectDelegate(string username,string address,int port,int server);
    delegate void EndConnectDelegate(bool res);
    delegate void FailedConnection();

    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
            InitInfo();
        }

        private void InitInfo()
        {
            string strHostName = Dns.GetHostName();

            IPHostEntry ipEntry = Dns.GetHostEntry(strHostName);
            IPAddress[] addr = ipEntry.AddressList;

            foreach (IPAddress ip in addr)
            {
                if (ip.GetAddressBytes().Length == 4)
                {
                    tb_address.Text = "tcp://" + ip.ToString();
                }
            }
        }

        private void CallBack(IAsyncResult res)
        {
            try
            {
                ConnectDelegate del = ((AsyncResult)res).AsyncDelegate as ConnectDelegate;
                bool re = del.EndInvoke(res);
                this.Invoke(new EndConnectDelegate(EndConnect),re);
            }
            catch (Exception e)
            {
                this.Invoke(new FailedConnection(Fail));
            }        
        }

        private void Fail()
        {
            MessageBox.Show("Erro na ligação ao servidor.", "Erro");
            this.button1.Enabled = true;
            Cursor = Cursors.Default;
        }

        private void EndConnect(bool res)
        {
            button1.Enabled = true;
            Cursor = Cursors.Default;
            if (res)
            {
                ProfileForm pb = new ProfileForm();
                pb.Owner = this;
                pb.Text = tb_username.Text + " (Cliente)";
                pb.Show();
                this.Visible = false;
            }
            else
            {
                MessageBox.Show("Não há servidores suficientes para iniciar o serviço.", "Erro");
            }
        }

        private void button1_Click(object sender, EventArgs e)
        {
            if (tb_address.Text.Length == 0)
            {
                MessageBox.Show("Tem de introduzir um endereço", "Erro", MessageBoxButtons.OK);
                return;
            }

            if (tb_username.Text.Length == 0)
            {
                MessageBox.Show("Tem de introduzir um username", "Erro", MessageBoxButtons.OK);
                return;
            }

            button1.Enabled = false;
            this.Cursor = Cursors.WaitCursor;

            int server = 1;
            if(rb_serv2.Checked)
                server = 2;
            else if(rb_serv3.Checked)
                server = 3;

            AsyncCallback ac = new AsyncCallback(CallBack);

            ConnectDelegate cd = new ConnectDelegate(Cliente.GetInstance().Connect);
                 
            cd.BeginInvoke(tb_username.Text, tb_address.Text,
                (int)tb_port.Value, server, ac, null);
        }

        private void rb_serv1_Click(object sender, EventArgs e)
        {
            rb_serv1.Checked = true;
            rb_serv2.Checked = false;
            rb_serv3.Checked = false;
        }

        private void rb_serv2_Click(object sender, EventArgs e)
        {
            rb_serv1.Checked = false;
            rb_serv2.Checked = true;
            rb_serv3.Checked = false;
        }

        private void rb_serv3_Click(object sender, EventArgs e)
        {
            rb_serv1.Checked = false;
            rb_serv2.Checked = false;
            rb_serv3.Checked = true;
        }

        private void tb_port_ValueChanged(object sender, EventArgs e)
        {
            decimal value = tb_port.Value;
            value = Math.Round(value / 10, 0) * 10;
            tb_port.Value = value;            
        }

        private void Form1_Load(object sender, EventArgs e)
        {

        }
    }
}
